import { defineStore } from 'pinia'
import { PROTECTION } from '@/utils/global'
import { usePlayerStore } from './player'

/**
 * tank头盔效果
 * 头盔效果会跟随指定的坦克
 */
export const useProtectionStore = defineStore('protection', {
  state: () => ({
    protections: new Map(),
    id: 0
  }),
  actions: {
    bornProtection(role = 1, type = 'born') {
      const playerStore = usePlayerStore()
      const p = playerStore.players.get(role)
      if (p.protection) {
        this.protections.delete(p.protectionId)
      }
      const o = {
        id: `player${role}_protection_${this.id}`,
        index: 0, // 0 or 1
        intervalProg: 0, // compare with interval
        totalProg: 0, // compare with dur
        role,
        type, // born or helmet
      }
      playerStore.updatePlayer({
        role,
        protection: true,
        protectionId: o.id
      })

      this.id++

      this.protections.set(role, o)
    },
    playProtection(ft) {
      this.protections.forEach(v => {
        const dur = PROTECTION.dur[v.type]
        const playerStore = usePlayerStore()

        if (v.totalProg >= dur) {
          playerStore.updatePlayer({
            role: v.role,
            protection: false,
            protectionId: ''
          })
          this.protections.delete(v.role)
        } else {
          const item = this.protections.get(v.role)
          item.totalProg += ft

          if (item.intervalProg >= PROTECTION.interval) {
            item.intervalProg = 0
            item.index = item.index === 0 ? 1 : 0
          } else {
            item.intervalProg += ft
          }

          this.protections.set(v.role, item)
        }
      })
    },
    updateProtection({ role = 1, ...params }) {
      const item = this.protections.get(role)
      this.protections.set(role, { ...item, ...params })
    },
  }
})